package com.yswl.pri.picture;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yswl.pri.R;
import com.yswl.pri.eventbus.PictureDialogEvent;
import com.yswl.pri.picture.entry.ImageBean;
import com.yswl.pri.picture.entry.ImageSourceCategory;
import com.yswl.pri.picture.entry.XiImageBean;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import yswl.com.klibrary.MApplication;
import yswl.com.klibrary.base.BaseRecyclerAdapter;
import yswl.com.klibrary.base.BaseViewHolder;
import yswl.com.klibrary.base.MFragment;
import yswl.com.klibrary.http.CallBack.HttpCallback;
import yswl.com.klibrary.http.HttpClientProxy;
import yswl.com.klibrary.http.okhttp.MScreenUtils;
import yswl.com.klibrary.util.L;
import yswl.com.klibrary.util.MUrlUtil;

/**
 * 来源：http://www.ximage.pro
 * 有问题
 */
@SuppressWarnings("图片加载不出来，来源方服务器错误")
public class PictureList4Fragment extends MFragment implements HttpCallback<JSONObject> {
    private static final String TAG = PictureList4Fragment.class.getSimpleName();
    private static final int LOAD_MORE = 1;
    private static final int REFRESH = 2;
    private static final String ARG_PARAM1 = "param1";

    private ImageSourceCategory mParam1;
    private int currPage = 0;


    public PictureList4Fragment() {
        // Required empty public constructor
    }

    public static PictureList4Fragment newInstance(ImageSourceCategory param1) {
        PictureList4Fragment fragment = new PictureList4Fragment();
        Bundle args = new Bundle();
        args.putSerializable(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = (ImageSourceCategory) getArguments().getSerializable(ARG_PARAM1);
        }
    }

    ImagsListAdapter mAdapter;
    RefreshLayout refreshLayout;
    PictureDialog dialogFrg;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_pic_list, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        //initUI
        refreshLayout = view.findViewById(R.id.refreshLayout);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                loadData(REFRESH);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                loadData(LOAD_MORE);
            }
        });
        RecyclerView recyclerView = view.findViewById(R.id.recyclerview);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        SpacesItemDecoration decoration = new SpacesItemDecoration(5);
        recyclerView.addItemDecoration(decoration);
        mAdapter = new ImagsListAdapter(getActivity(), mImages, R.layout.adapter_image_list_item);
        mAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(final int position) {
                MApplication.getApplication().getGolbalHander().post(new Runnable() {
                    @Override
                    public void run() {
                        if (dialogFrg == null)
                            dialogFrg = PictureDialog.getInstance();
                        dialogFrg.show(getChildFragmentManager(), "xiimage");
                        PictureDialogEvent.postEvent(defultImagBean, position);
                    }
                });
            }
        });
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mAdapter);
        refreshLayout.autoRefresh();
    }

    List<ImageBean> defultImagBean = new ArrayList<>();

    List<ImageBean> copyImageData() {
        List<XiImageBean> baiduImageBeans = mAdapter.getList();
        List<ImageBean> imageBeans = new ArrayList<>();
        for (int i = 0; i < baiduImageBeans.size(); i++) {
            XiImageBean currBai = baiduImageBeans.get(i);
            ImageBean currIma = new ImageBean();
            currIma.image_url = currBai.getLarge_image();
            currIma.image_height = currBai.getLarge_height();
            currIma.image_width = currBai.getLarge_width();
            imageBeans.add(currIma);
        }
        return imageBeans;
    }

    private void loadData(int Mode) {
        if (Mode == LOAD_MORE) currPage++;
        if (Mode == REFRESH) currPage = 1;
        String url = null;
        if (mParam1 == ImageSourceCategory.HOT) {
            url = MUrlUtil.getUrl(this, R.string.url_xi_hot_image_search);
            url = MUrlUtil.setParam(url, "page", currPage);
        }
        if (mParam1 == ImageSourceCategory.LAST) {
            url = MUrlUtil.getUrl(getActivity(), R.string.url_xi_lattest_image_search);
            url = MUrlUtil.setParam(url, "page", currPage);
        }
        if (mParam1 == ImageSourceCategory.RECOMMED) {
            url = MUrlUtil.getUrl(this, R.string.url_xi_recommend_image_search);
            url = MUrlUtil.setParam(url, "page", currPage);
        }
        if (mParam1 == ImageSourceCategory.RODM) {
            url = MUrlUtil.getUrl(this, R.string.url_xi_random_image_search);
            url = MUrlUtil.setParam(url, "page", currPage);
        }
        HttpClientProxy.getInstance().getAsyn(url, Mode, null, this);
    }

    ArrayList<XiImageBean> mImages;

    @Override
    public void onSucceed(int requestId, JSONObject result) {
        L.e(TAG, " onSucceed : " + result);
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        if (result == null) return;
        int total = result.optInt("total");
        if (total > 0) {
            if (requestId == REFRESH) {
                mImages = XiImageBean.jsonToList(result);
                mAdapter.setList(mImages);
            } else {
                mImages = XiImageBean.jsonToList(result);
                mAdapter.addList(mImages);
            }
            defultImagBean = copyImageData();
        }

    }

    @Override
    public void onFail(int requestId, String errorMsg) {
        L.e(TAG, " onFail : " + errorMsg);
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
    }

    public class ImagsListAdapter extends BaseRecyclerAdapter<XiImageBean> {

        int widht;

        public ImagsListAdapter(Context mContext, List<XiImageBean> mList, int itemLayoutId) {
            super(mContext, mList, itemLayoutId);
            widht = MScreenUtils.getScreenWidth(mContext);
            L.d("TAG", " 屏幕width :" + widht);
        }

        @Override
        public void onBind(BaseViewHolder holder, XiImageBean imag, int position) {
            ImageView imageView = holder.findById(R.id.image);
            ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
            double currWidth = imag.getLarge_width();
            double currHeight = imag.getLarge_height();
            if (imag.getLarge_width() < widht) {
                currWidth = widht;
                currHeight = (widht / (double) imag.getLarge_width()) * imag.getLarge_height();
            }
            layoutParams.width = (new Double(currWidth)).intValue();
            layoutParams.height = (new Double(currHeight)).intValue();

            L.e("TAG", String.format(" width :%1$s, height :%2$s", imag.getLarge_width(), imag.getLarge_height()));
            L.e("TAG", String.format("new width :%1$s,new height :%2$s", currWidth, currHeight));
            Glide.with(mContext).applyDefaultRequestOptions(new RequestOptions().override(layoutParams.width, layoutParams.height)).load(imag.getLarge_image()).into(imageView);
        }
    }
}
